﻿
function customAjax(url, Id, data) {
    var ajax = $.ajax({
        type: 'get',
        url: url,
        async: 'false',
        dataType: "html",
        timeout: 20000,
        xhrFields: {
            withCredentials: true
        },
        success: function (data) {
            $("#" + Id + "").empty();
            $("#" + Id + "").html(data);
        },
        error: function (err) {
        }
    });
}

function SetDateRange(startElem, endElem) {
    layui.use(['laydate'], function () {
        //日期控件渲染
        var laydate = layui.laydate;

        var start = laydate.render({
            elem: startElem,
            btns: ['clear', 'confirm'],
            done: function (value, datas) {
                if (value != "") {
                    end.config.min.year = datas.year;
                    end.config.min.month = datas.month - 1;
                    end.config.min.date = datas.date;
                }
            }
        });
        var end = laydate.render({
            elem: endElem,
            btns: ['clear', 'confirm'],
            done: function (value, datas) {
                if (value != "") {
                    start.config.max.year = datas.year;
                    start.config.max.month = datas.month - 1;
                    start.config.max.date = datas.date;
                }
            }
        });

    });
}

/*
 * 获取获取地址栏参数
 * 使用：GetQueryString("参数名1")
 */
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}

//表单查看时，禁用文本框
function setDisabledToForm(formId) {
    $("#" + formId + " input").attr("disabled", "disabled").addClass("disabled");
    $("#" + formId + " select").attr("disabled", "disabled").addClass("disabled");
    $("#" + formId + " textarea").attr("disabled", "disabled").addClass("disabled");
    $("#" + formId + " a").addClass("layui-btn-disabled");
    $("#" + formId + " button").addClass("layui-btn-disabled");
}
//转化日期

function getTimeByStampChinese(str, format) {
    if (str == null || str == "")
        return "";
    if (str.indexOf("Date(") >= 0) {
        str = parseInt(str.substr(6, 13));
    }
    var date = new Date(str);
    Y = date.getFullYear();
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    D = date.getDate().toString().length < 2 ? "0" + date.getDate() : date.getDate();
    h = date.getHours().toString().length < 2 ? "0" + date.getHours() : date.getHours();
    m = date.getMinutes().toString().length < 2 ? "0" + date.getMinutes() : date.getMinutes();
    s = date.getSeconds().toString().length < 2 ? "0" + date.getSeconds() : date.getSeconds();
    if (format == "ymd") {
        return Y + '年' + M + '月' + D + "日";;
    }
    else if (format == "ym") {
        return Y + '年' + M + '月';
    }
    else if (format == "ymdhms") {
        return Y + '年' + M + '月' + D + '日' + h + ':' + m + ':' + s;
    }
    else if (format == "ymdhm") {
        return Y + '年' + M + '月' + D + '日' + h + ':' + m;
    }
    else {
        return Y + '年' + M + '月' + D + '日' + h + ':' + m + ':' + s;
    }

}
//class名
//e 控件id或class type：控件类型
function setCtrDisabled(e, type) {
    if (type && type != "") {
        $(e + " " + type).attr("disabled", "disabled");
    } else {
        $(e + " input").attr("disabled", "disabled");
        $(e + " select").attr("disabled", "disabled");
        $(e + " textarea").attr("disabled", "disabled");
        $(e + " a").addClass("layui-btn-disabled");
        $(e + " button").addClass("layui-btn-disabled");
        $(e + " ul").attr("disabled", "disabled");
    }

}

/*
 * formId 最外层表单名称
 * element
 */
function setFormDisabled(formId) {
    var data = $(formId).find($(":input"));
    $(data).each(function (index, item) {
        if (item.nodeName == "SELECT") {
            $(formId).find("div").css("pointer-events", "none");
        }
        $(this).css("pointer-events", "none");
        $(this).attr("disabled", "true");
    });
}

function setFormElement(element) {
    $(element).css("pointer-events", "none");
}

function setDisableBtn(element) {
    $(element).css("pointer-events", "none");
    $(element).addClass("layui-btn-disabled");
}

//去除按钮不可用
function removeDisableBtn(element) {
    $(element).removeAttr("style");
    $(element).removeClass("layui-btn-disabled");
}

/*通用加载下拉框*/
//ids: html页面上需要填充数据的select的id
//codeType： 字典类型
//isAll:是否自动加个全部的选项(默认true)
//codes:指定的code（多个逗号隔开）
function initSelectbox(ids, codeType, isAll, codes) {
    if (!ids) {
        return;
    }
    var ids = ids.split(',');
    for (var i = 0; i < ids.length; i++) {
        $("#" + ids[i]).html("");
    }
    var url = '/ListCode/GetListCode?rdo=' + Math.random();
    $.ajax({
        type: "GET",
        url: url,
        contentType: "application/json;charset=utf-8",
        data: { CodeType: codeType, Codes: codes },
        async: false,
        success: function (data) {
            var list = data;
            var options = "";
            if (typeof isAll == 'undefined' || isAll == true) {
                options = "<option value=''>--全部--</option>";
            }

            if (list == null || list.length == 0) {
                for (var i = 0; i < ids.length; i++) {
                    $("#" + ids[i]).append(options);
                }
                renderSelect();
                return;
            }
            for (var i = 0; i < ids.length; i++) {
                var ddl = $("#" + ids[i]);
                if (ddl) {
                    for (var k = 0; k < list.length; k++) {
                        options += "<option value='" + list[k].Code + "'>" + list[k].CodeName + "</option>";
                    }

                    ddl.append(options);
                    renderSelect();
                }
            }
        }
    });
}

/*
 * 重新渲染下拉框
 */
function renderSelect(ctrl) {
    layui.use('form', function () {
        var form = layui.form;
        if (typeof ctrl == 'undefined' || ctrl == "" || ctrl == null) {
            form.render("select");
        } else {
            form.render(ctrl);
        }
    });
}

/*请求后台方法*/
function AjaxPost(url, data, appendDiv, successFun, errorFun, aysnc) {
    var index = 0;
    //是否异步（如果没有传值默认异步）
    if (aysnc == undefined || aysnc == null) {
        aysnc = true;
    }
    $.ajax({
        url: url,
        data: data,
        dataType: 'json',
        type: 'post',
        async: aysnc,
        beforeSend: function (data) {
            //开启遮罩层
            LoadingModelPage(true, appendDiv);
        },
        success: function (data) {
            successFun(data);
        },
        error: function (e) {
            errorFun(e);
        },
        complete: function (XMLHttpRequest, textStatus) {
            //关闭遮罩层
            LoadingModelPage(false, appendDiv);
        }
    });
}

/*请求后台方法*/
function AjaxPost(url, data, appendDiv, successFun, errorFun, aysnc, requestGet) {
    var index = 0;
    if (requestGet) {
        requestGet = 'get';
    } else {
        requestGet = 'post';
    }
    //是否异步（如果没有传值默认异步）
    if (aysnc == undefined || aysnc == null) {
        aysnc = true;
    }
    $.ajax({
        url: url,
        data: data,
        dataType: 'json',
        type: requestGet,
        async: aysnc,
        beforeSend: function (data) {
            //开启遮罩层
            LoadingModelPage(true, appendDiv);
        },
        success: function (data) {
            successFun(data);
        },
        error: function (e) {
            errorFun(e);
        },
        complete: function (XMLHttpRequest, textStatus) {
            //关闭遮罩层
            LoadingModelPage(false, appendDiv);
        }
    });
}
/*
 * 编辑的时候给表单赋值
 * formId:表单ID
 * data：json字符串
 */
function setValueToForm(formId, data) {
    //data = JSON.parse(data);//根据ID获取对象后已是JSON格式，不需要转换JSON
    //给input文本框的赋值
    if ($("#" + formId + " input").length > 0) {
        $("#" + formId + " input").each(function () {
            try {
                //新增的时候，主键ID或者没有的字段会报错。
                if ($(this).attr("type") == "text" || $(this).attr("type") == "tel" || $(this).attr("type") == "number" || $(this).attr("type") == "email" || $(this).attr("type") == "hidden") {
                    if ($(this).attr("data-type") == "date") {
                        var time = getTimeByStamp(data[$(this).attr("id")], 'ymd');
                        $(this).val(time);
                    }
                    else if ($(this).attr("dt-type")) {
                        var time = getTimeByStamp(data[$(this).attr("id")], $(this).attr("dt-type"));
                        $(this).val(time);
                    }
                    else {
                        $(this).val(data[$(this).attr("id")]);
                    }
                }
                //处理开关
                if ($(this).attr("type") == "checkbox" && $(this).attr("class") == "swicth") {
                    if (data[$(this).attr("id")] == null || data[$(this).attr("id")] == "" || data[$(this).attr("id")] == 0) {
                        //无效
                        $(this).prop("checked", false);
                    }
                    else {
                        $(this).prop("checked", true);
                    }
                    renderSelect('checkbox');
                }
                if ($(this).attr("type") == "radio") {
                    if ($(this).val() == data[$(this).attr("name")]) {
                        $(this).attr("checked", "");
                    } else {
                        $(this).removeAttr("checked");
                    }
                    renderSelect('radio');
                }
            } catch (e) {

            }
        });
    }

    //给select下拉框赋值
    if ($("#" + formId + " select").length > 0) {
        $("#" + formId + " select").each(function () {
            var id = $(this).attr("id");
            $(this).find("option").each(function () {
                try {
                    $(this).attr("selected", false);
                    if ($(this).val() == data[id]) {
                        $(this).attr("selected", true);
                    }
                } catch (e) {

                }
            });
        });

        setTimeout(function () {
            renderSelect();
        }, 200);
    }

    //给textarea文本域赋值
    if ($("#" + formId + " textarea").length > 0) {
        $("#" + formId + " textarea").each(function () {
            try {
                $(this).val(data[$(this).attr("id")]);
            } catch (e) {

            }
        });
    }
}

function getFormatDate(str, format) {

    if (!str || str.length == 0) {
        str = new Date();
    }
    var year = str.getFullYear();
    var month = str.getMonth() + 1 < 10 ? "0" + (str.getMonth() + 1) : str.getMonth() + 1;
    var date = str.getDate() < 10 ? "0" + str.getDate() : str.getDate();
    var hour = str.getHours() < 10 ? "0" + str.getHours() : str.getHours();
    var minute = str.getMinutes() < 10 ? "0" + str.getMinutes() : str.getMinutes();
    var second = str.getSeconds() < 10 ? "0" + str.getSeconds() : str.getSeconds();

    if (format == "ymd") {
        return year + "-" + month + "-" + date;
    } else if (format == "y") {
        return year;
    } else if (format == "m") {
        return month;
    }
    else if (format == "d") {
        return date;
    }
    else if (format == "ymdhms") {
        return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
    }
}


//将时间撮转成日期时间格式
//str 时间撮
//format 日期时间格式：如年月日用：ymd  ； 年月日时分秒用：ymdhms;
function getTimeByStamp(str, format) {
    if (str == null || str == "")
        return "";
    if (str.indexOf("Date(") >= 0) {
        str = parseInt(str.substr(6, 13));
    }
    var date = new Date(str);
    Y = date.getFullYear();
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    D = date.getDate().toString().length < 2 ? "0" + date.getDate() : date.getDate();
    h = date.getHours().toString().length < 2 ? "0" + date.getHours() : date.getHours();
    m = date.getMinutes().toString().length < 2 ? "0" + date.getMinutes() : date.getMinutes();
    s = date.getSeconds().toString().length < 2 ? "0" + date.getSeconds() : date.getSeconds();
    if (format == "ymd") {
        return Y + '-' + M + '-' + D;
    }
    else if (format == "ym") {
        return Y + '-' + M;
    }
    else if (format == "ymdhms") {
        return Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s;
    }
    else if (format == "ymdhm") {
        return Y + '-' + M + '-' + D + ' ' + h + ':' + m;
    }
    else {
        return Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s;
    }
}

//图片信息转换
function getPicture(value) {
    if (value == null) {
        return '';
    }
    var fileInfos = JSON.parse(value);
    return '<img src="' + jypath + fileInfos[0].url
        + '" style="width:25px;height:25px;"/>';
}

//关闭当前弹出框
function closeThisPop() {
    var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
    parent.layer.close(index); //再执行关闭
}

//list页面批量删除的时候，调用这个方法时传参数过来
function search(isList) {
    if (typeof isList != 'undefined') {
        isReload = false;
    }
    else {
        isReload = true;
    }
    $("#search").trigger("click");
}

//控制控件显示或者隐藏
//e1 控件名
//display true或false
function ctrlDisOrHidd(el, display) {
    if (display == true) {
        $(el).show();
    } else {
        $(el).hide();
    }
}

//控制只能输入整数
function allowNumber(el) {
    $(el).keyup(function () {
        var tmptxt = $(this).val();
        $(this).val(tmptxt.replace(/\D|^0/g, ''));
    }).bind("paste", function () {
        var tmptxt = $(this).val();
        $(this).val(tmptxt.replace(/\D|^0/g, ''));
    }).css("ime-mode", "disabled");
}
//控制只能输入数字和小数点
function allowNumAndDec(el) {
    $(el).keyup(function () {
        num($(this)[0]);
    }).bind("paste", function () {
        num($(this)[0]);
    }).css("ime-mode", "disabled"); //CSS设置输入法不可用
}

function num(obj) {
    obj.value = obj.value.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
    obj.value = obj.value.replace(/^\./g, ""); //验证第一个字符是数字
    obj.value = obj.value.replace(/\.{2,}/g, "."); //只保留第一个, 清除多余的
    obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    obj.value = obj.value.replace(/^(0)*([1-9]+\..*)$/, '$2'); //删除整数位的冗余0
    obj.value = obj.value.replace(/^(0)*([0]{1}\..*)$/, '$2'); //删除整数位的冗余0
    obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
}

function allowNumAndDecMoney(el) {
    $(el).keyup(function () {
        num1($(this)[0]);
    }).css("ime-mode", "disabled"); //CSS设置输入法不可用
}

function num1(obj) {
    var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
    setTimeout(function () {
        if (!reg.test(obj.value)) {
            console.log(obj.value)
            obj.value = ''
        } else {
            console.log(obj.value)
        }
    }, 2000);
}

// 去除undefined 空值 空格等
function trimUndefined(str) {
    if (str == undefined) {
        return ""
    } else if (str == "undefined") {
        return ""
    } else if (str == null) {
        return ""
    } else if (str == "null") {
        return ""
    } else {
        return str
    }
}

// 去除undefined 空值 空格等
function requiredCheck(str) {
    if (trimUndefined(str).length > 0) {
        return true;
    }
    return false;
}


//layui table表格的单元行点击事件
//子页面用的时候，只需要判断layTableLineData这个值是否有就行了
function layTableLineClick(e, jsonStr) {
    jsonStr = unescape(jsonStr);
    jsonStr = JSON.parse(jsonStr);
    delete jsonStr.LAY_TABLE_INDEX;
    layTableLineData = jsonStr;
    $(e).parent().find("tr:not(.last)").removeAttr('style');
    //备用颜色值：#FFE48D   #EAF2FF
    $(e).css("background-color", "#b2f0e8");
}

//判断是否是IE浏览器  返回的值为-1 说明不是ie浏览器
function IEVersion() {
    var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
    var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器
    var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器
    var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
    if (isIE) {
        var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
        reIE.test(userAgent);
        var fIEVersion = parseFloat(RegExp["$1"]);
        if (fIEVersion == 7) {
            return 7;
        } else if (fIEVersion == 8) {
            return 8;
        } else if (fIEVersion == 9) {
            return 9;
        } else if (fIEVersion == 10) {
            return 10;
        } else {
            return 6;//IE版本<=7
        }
    } else if (isEdge) {
        return 'edge';//edge
    } else if (isIE11) {
        return 11; //IE11
    } else {
        return -1;//不是ie浏览器
    }
}

/**
 * 将form表单中的字段组合成json串。
 * @formId {string} 查询表单的ID
 * @others {json} 其它的json值
 */
function fromStrToJson(formId, others) {
    var array = $("#" + formId).serializeArray();
    if (array.length > 0) {
        var newJson = {};
        array.forEach(function (value, key, map) {
            newJson[value.name] = $.trim(value.value);
        });
        if (others != "") {
            newJson = $.extend(others, newJson);
        }
        return newJson;
    }
    else {
        return "";
    }
}

/**
 * 单文件或单图片上传
 * @param {bool} 类型，是否自动上传，false的场合需要填入"bindAction"参数
 * @param {string} 页面上的选择文件或图片的元素ID
 * @param {string} 后台接口地址
 * @param {string} 类型，是图片还是文件，值为file/images
 * @param {string} 页面上触发上传的元素ID（如保存）
 * @param {function} 选择文件后触发的方法,会回传两个参数（file, result），file是文件流，result是base64的图片（如果是图片）
 * @param {function} 上传成功后的回调方法，返回json参数。
 * @param {function} 上传失败后的回调方法，无返回参数。
 * @param {int} 限制上传的文件或者图片大小，只能输入数字，传1代表只能上传1M的文件。
 * @param {string} 限制上传的文件或者图片的后缀名，不传就默认。
 */
function fileAndImgUpload(auto, elemId, url, type, bindAction, selectFun, doneSuccessFun, doneErrorFun, limitSize, extname) {
    var accept = "images";
    var exts = "jpg|png|gif|bmp|jpeg";
    //默认图片
    if (type == "file") {
        accept = "file";
        exts = "doc|docx|zip|rar|7z|xls|xlsx|txt|pdf";
    }
    //拓展名
    if (extname) {
        exts = extname;
    }

    layupload.render({
        elem: '#' + elemId,
        url: url,
        accept: accept,
        exts: exts,
        multiple: false,
        auto: auto,
        size: limitSize * 1024,//单位kb
        bindAction: '#' + bindAction,
        choose: function (obj) {
            //读取本地文件
            obj.preview(function (index, file, result) {
                selectFun(file, result);
            });
        },
        done: function (res, index, upload) {
            if (res.code == 1) {
                //上传成功
                doneSuccessFun(res);
                return;
            }
            this.error();
        },
        error: function () {
            doneErrorFun();
        }
    });
}

/**
 * 下拉框选择树形结构列表
 * @param {id} ztree对象的id
 * @param {url} ztree对象的取值Url
 * @param {param} ztree对象的取值条件
 * @param {callback} 返回的值（onclick）
 * @param {checkenable} 是否有复选框
 * @param {selectNodeID} 默认选中的节点ID
 */
function ZtreeList(id, url, param, callback, checkenable, selectNodeID) {
    $.ajax({
        url: url,
        data: param,
        type: "POST",
        aysnc: false,
        success: function (data) {
            if (data.length > 0) {
                var setting = {
                    check: {
                        enable: checkenable
                    },
                    data: {
                        simpleData: {
                            enable: true,
                            //主键ID
                            idKey: "id",
                            //parentId
                            pIdKey: "pId",
                            //跟节点的parentId值(可以是0，也可以是其它值，但是传出来的数据的根节点的值也一定要是跟设置的值相等。)
                            rootPId: 0
                        },
                        key: {
                            icon: "icon",
                            checked: "IsChecked"
                        }
                    },
                    callback: {
                        //每一项的点击事件
                        onClick: callback,
                        //默认选中
                        onNodeCreated: function (event, treeId, treeNode) {
                            if (selectNodeID != null && selectNodeID != '') {
                                if (treeNode.id.indexOf(selectNodeID) >= 0) {
                                    $("#" + treeNode.tId + "").find(">a").addClass("curSelectedNode");
                                    $("#treeName").val(treeNode.name); //保存选中节点名称的input
                                    $("#treeId").val(id);//保存选中节点id的input
                                }
                            }
                        },
                    }
                };
                //拿到数据初始化树形控件
                var treeObj = $.fn.zTree.init($("#" + id), setting, data);
                //展开所有（参数false为不展开所有）
                treeObj.expandAll(true);
                setSize();
                arrowClick();
            }
        },
        error: function (e) {
            console.log(e);
        }
    });
}

/**
 * 点击下拉框显示树形离开隐藏树形
 * @param {id} id
 * @param {zNodes} 要传的数据
 * @param {callback} 返回的值
 */
function SelectZtree(eventId, showId, hideId) {
    $(eventId).click(function () {
        if (!$(this).parent().find(showId).is(":animated"))
            $(this).parent().find(showId).animate({ "height": "toggle" }, 300);
    });
    $(hideId).hover(function () { }, function () {
        $(this).find(showId).hide();
    });
}

//遮罩层
function LoadingModelPage(bFlg, appendDiv) {
    if (appendDiv == undefined) appendDiv = "body";

    if (bFlg == false) {
        $("#loadingModelPage").remove();
        return;
    }
    var is = $("#loadingModelPage").length > 0;
    if (is == false) {
        var load = '<div id="loadingModelPage" style="position: absolute; left: 0px; top: 0px; width: 100%; height: 100%; background: rgba(0,0,0,0.3); z-index: 9999; display: block;"><div style="position: relative; left: 0px; top: 0px; width: 100%; height: 100%; display: flex; justify-content: center; align-items: Center;"><i class ="fa-li fa fa-spinner fa-spin" style="font-size: 45px; position: absolute; left: 50%; top: 50%; width: 50px; height: 50px; color: #fff; margin-left: -25px; margin-top: -25px;"></i><p style="color: #fff; margin-top: 70px;">数据正在处理中，请稍等。</p></div></div>';
        $(appendDiv).append(load);
    } else {
        $("#loadingModelPage").show();
    }
}

/*********************** 输入检查***********************/
//检查电话号码
function TelRegCheck(obj) {
    var str = obj;
    var reg = /^0\d{2,3}-?\d{7,8}$/;;
    var flag = reg.test(str);
    if (flag == false) {
        reg = /^1\d{10}$/;
        flag = reg.test(str);
    }
    if (flag == false) {
        return "电话号码格式不正确";
    }
    return "";
}

//检查身份证号
function IdCardRegCheck(card) {
    var msg = "身份证格式不正确";

    var
        vcity = {
            11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古",
            21: "辽宁", 22: "吉林", 23: "黑龙江", 31: "上海", 32: "江苏",
            33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东",
            41: "河南", 42: "湖北", 43: "湖南", 44: "广东", 45: "广西",
            46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南",
            54: "西藏", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏",
            65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外"
        },


        //检查号码是否符合规范，包括长度，类型
        isCardNo = function (card) {
            //身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
            var reg = /(^\d{15}$)|(^\d{17}(\d|X|x)$)/;
            if (reg.test(card) === false) {
                return false;
            }
            return true;
        },

        //取身份证前两位,校验省份
        checkProvince = function (card) {
            var province = card.substr(0, 2);
            if (vcity[province] == undefined) {
                return false;
            }
            return true;
        },

        //检查生日是否正确
        checkBirthday = function (card) {
            var len = card.length;
            //身份证15位时，次序为省（3位）市（3位）年（2位）月（2位）日（2位）校验位（3位），皆为数字
            if (len == '15') {
                var re_fifteen = /^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/;
                var arr_data = card.match(re_fifteen);
                var year = arr_data[2];
                var month = arr_data[3];
                var day = arr_data[4];
                var birthday = new Date('19' + year + '/' + month + '/' + day);
                return verifyBirthday('19' + year, month, day, birthday);
            }
            //身份证18位时，次序为省（3位）市（3位）年（4位）月（2位）日（2位）校验位（4位），校验位末尾可能为X
            if (len == '18') {
                var re_eighteen = /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9Xx])$/;
                var arr_data = card.match(re_eighteen);
                var year = arr_data[2];
                var month = arr_data[3];
                var day = arr_data[4];
                var birthday = new Date(year + '/' + month + '/' + day);
                return verifyBirthday(year, month, day, birthday);
            }
            return false;
        },

        //校验日期
        verifyBirthday = function (year, month, day, birthday) {
            var now = new Date();
            var now_year = now.getFullYear();
            //年月日是否合理
            if (birthday.getFullYear() == year && (birthday.getMonth() + 1) == parseInt(month) && ((birthday.getDate() + 1) == parseInt(day) || (birthday.getDate()) == parseInt(day))) {
                //判断年份的范围（3岁到100岁之间)
                var time = now_year - year;
                if (time >= 3 && time <= 100) {
                    return true;
                }
                return false;
            }
            return false;
        },

        //15位转18位身份证号
        changeFivteenToEighteen = function (card) {
            if (card.length == '15') {
                var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
                var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
                var cardTemp = 0, i;
                card = card.substr(0, 6) + '19' + card.substr(6, card.length - 6);
                for (i = 0; i < 17; i++) {
                    cardTemp += card.substr(i, 1) * arrInt[i];
                }
                card += arrCh[cardTemp % 11];
                return card;
            }
            return card;
        },

        //校验位的检测
        checkParity = function (card) {
            //15位转18位
            card = changeFivteenToEighteen(card);
            var len = card.length;
            if (len == '18') {
                var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
                var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
                var cardTemp = 0, i, valnum;
                for (i = 0; i < 17; i++) {
                    cardTemp += card.substr(i, 1) * arrInt[i];
                }
                valnum = arrCh[cardTemp % 11];
                if (valnum == card.substr(17, 1)) {
                    return true;
                }
                return false;
            }
            return false;
        };
    //是否为空
    if (!card) {
        return msg;
    }
    card = card.toUpperCase();
    //校验长度，类型
    if (!isCardNo(card)) {
        return msg;
    }
    //检查省份
    if (!checkProvince(card)) {
        return msg;
    }
    //校验生日
    if (!checkBirthday(card)) {
        return msg;
    }
    //检验位的检测
    if (!checkParity(card)) {
        return msg;
    }
    return "";
}

//检查EMAIL
function EmailRegCheck(obj) {
    var str = obj;
    var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
    var flag = reg.test(str);
    if (flag == false) {
        return "邮箱格式不正确";
    }
    return "";
}

//检查邮编
function ZipCodeCheck(value) {
    var re = /^[1-9][0-9]{5}$/
    if (re.test(value) == false) {
        return "邮政编码格式不正确！";
    }
    return "";
}

//序号检查
function checkOrderID(value, max) {
    var maxvalue = 2147483647;
    if (max != null) {
        maxvalue = parseInt(max);
    }
    var nubmer = parseInt(value);
    if (isNaN(nubmer) || nubmer <= 0 || !(/^\d+$/.test(nubmer))) {
        return "只允许输入不超过" + maxvalue + "的整数!";
    }
    if (nubmer > maxvalue) {
        return "输入值不能超过" + maxvalue;
    }
    return "";
}

//特殊字符转义
function escapeJquery(srcString) {
    // 转义之后的结果
    var escapseResult = srcString;
    // jquery中的特殊字符,不是正则表达式中的特殊字符
    var jquerySpecialChars = ["<", ">"];
    for (var i = 0; i < jquerySpecialChars.length; i++) {
        escapseResult = escapseResult.replace(new RegExp(jquerySpecialChars[i],
            "g"), "\\" + jquerySpecialChars[i]);
    }
    return escapseResult;
}

//特殊字符检查
function checkSpecialChar(value) {
    var reg = /<[a-zA-Z]/g;
    var result = reg.test(value);
    if (result == true) {
        return "输入内容包含特殊字符";
    }
    return "";
}

//字符串长度检测汉字算两个
function getByteLen(value) {
    var len = 0;
    for (var i = 0; i < value.length; i++) {
        var a = value.charAt(i);
        if (a.match(/[^\x00-\xff]/ig) != null) {
            len += 2;
        }
        else {
            len += 1;
        }
    }
    return len;
}

//文字特殊字符及最大长度检测
function checkStr(value, maxlength) {
    if (value.trim() == "") {
        return "";
    }
    if (maxlength) {
        var len = getByteLen(value);
        if (len > maxlength) {
            return "输入文字超过最大长度" + maxlength + "！";
        }
    }
    return checkSpecialChar(value);
}
/*********************** 输入检查结束***********************/

//上传
//formName: 表单名称
//ctrId ：文件路径显示框ID
//Resourcetype： 总分类  SystemResource/ProjectResource
//ChildDir: 子目录分类   系统管理资源： Menu  Project User;  项目资源：图纸 模型 视频 文档
//data: 包括附件表 OwerID，MainCate，SubCate等，如果需要写入附件表三个必须
//fileID:文件控[input type='file']件的名称 (name)
function UploadFile(formName, ctrId, Resourcetype, ChildDir, data, fileID) {
    var formData = new FormData(document.forms.namedItem(formName));
    //向form添加总分类 系统管理资源或者项目资源
    formData.append(ConstBase.RESOURCE_TYPE_PARAMNAME, Resourcetype)
    //向form添加子分类 如 系统管理资源下的用户头像，菜单logon等
    formData.append(ConstBase.RESOURCE_TYPE_CHILDDIR, ChildDir)
    if (data != null) {
        //附件表数据
        formData.append("Attachment", JSON.stringify(data));
    }

    //获取文件名
    var filename = document.forms.namedItem(formName)[fileID].value.toLowerCase();
    //附件表数据
    formData.append("FileID", fileID);
    var filenamearray = filename.split('\\');
    filename = filenamearray[filenamearray.length - 1];
    if (Resourcetype == ConstBase.RESOURCE_TYPE_SYSTEMP) { //图片文件格式检查
        if (!CheckImge(filename)) {
            $('#' + fileID).val('');
            return;
        }
    }
    else if (Resourcetype == ConstBase.RESOURCE_TYPE_PROJECT && !CheckProjectFile(filename, ChildDir)) { //项目文件格式检查
        $('#' + fileID).val('');
        return;
    }

    LoadingModelPage(true);
    $.ajax({
        url: "/Base/Upload/UploadFile",
        type: 'POST',
        cache: false,
        data: formData,
        headers: {
            Accept: "multipart/form-data"
        },
        processData: false,
        contentType: false,
        dataType: "json",
        success: function (rtndata) {
            if (rtndata.code = Const.SUCCESS) {
                $("#" + ctrId).val(rtndata.Message);
                $("#" + ctrId).siblings("[type='text']").val(filename);
                if ($("#" + ctrId).siblings("img") != undefined) {
                    $("#" + ctrId).siblings("img").attr("src", rtndata.Message);
                }
                return;
            }
            layWin.showMsg(rtndata.Message, 5);
            return;
        },
        error: function (msg) {
            layWin.showMsg("文件上传失败", 5);
            return;
        }, complete: function (data) {
            LoadingModelPage(false);
        }
    });
}

//检查图片格式
function CheckImge(fileName) {
    //分割上传文件字符串  userfile的value为上传文件的名称 类型为字符串。
    var fileNameArr = fileName.split('.');
    //文件名后缀
    var suffix = fileNameArr[fileNameArr.length - 1];
    //如果后缀为空
    if (suffix == "") {
        layWin.showMsg("图片后缀不能为空！", 5);
        return false;
    }
    if (!(suffix == 'gif' || suffix == 'jpg' || suffix == 'bmp' || suffix == 'png' || suffix == 'jpeg')) {
        layWin.showMsg("请选择格式为*.jpg、*.gif、*.bmp、*.png、*.jpeg 的图片", 5);
        return false;
    }
    return true;
}

//检查文件格式
function CheckProjectFile(fileName, fileType) {
    //分割上传文件字符串  userfile的value为上传文件的名称 类型为字符串。
    var fileNameArr = fileName.split('.');
    //或者document.getElementById("userfile")	也可以获得该dom元素
    //文件名后缀
    var suffix = fileNameArr[fileNameArr.length - 1];
    //如果后缀为空
    if (suffix == "") {
        layWin.showMsg("文件后缀不能为空！", 5);
        return false;
    }
    var allowExtensionName = "";
    if (fileType == ConstListCode.CODETYPE_RESOURCETYPE_DWG) {
        allowExtensionName = ConstBase.RESOURCEFILE_DWG_SUFFIX;
    }
    else if (fileType == ConstListCode.CODETYPE_RESOURCETYPE_RVT) {
        allowExtensionName = ConstBase.RESOURCEFILE_MODEL_SUFFIX;
    }
    else if (fileType == ConstListCode.CODETYPE_RESOURCETYPE_VIDEO) {
        allowExtensionName = ConstBase.RESOURCEFILE_DWG_VIDEO;
    }

    if (allowExtensionName == "") {
        return true;
    }
    if (allowExtensionName.indexOf(suffix) < 0) {
        layWin.showMsg("请选择格式为" + allowExtensionName + "的文件", 5);
        return false;
    }
    return true;
}

//格式化文件大小
function formatFileSize(FileSize) {
    if (FileSize == '') {
        return FileSize;
    }
    var size = FileSize / 1024 / 1024;
    if ((parseFloat(size) * 100) < 100.0) {
        size = FileSize / 1024;
        return Math.round(size * 100) / 100 + "Kb";
    }
    else {
        return Math.round(size * 100) / 100 + "Mb";
    }
}

function SetAuthority(btnStyle, btnId) {
    //是否已经加载了权限
    if ($("#AuthorityCodes") == undefined || $("#AuthorityCodes") == null) {
        GetAuthority();
    }
    var data = $("#AuthorityCodes").val();
    if (btnStyle != null && btnStyle != "") {
        var styles = btnStyle.split(",");
        for (var i = 0; i < styles.length; i++) {
            $("." + styles[i]).each(function () {
                var authorityCode = $(this).attr("data-authority");
                if (authorityCode != undefined && authorityCode != null && authorityCode != "") {
                    if (data.indexOf(authorityCode) >= 0) {
                        $(this).show();
                    }
                }
            });
        }
    }
    if (btnId != null && btnId != "") {
        var ids = btnId.split(",");
        for (var i = 0; i < ids.length; i++) {
            $("#" + ids[i]).each(function () {
                var authorityCode = $(this).attr("data-authority");
                if (authorityCode != undefined && authorityCode != null && authorityCode != "") {
                    if (data.indexOf(authorityCode) >= 0) {
                        $(this).show();
                    }
                }
            });
        }
    }
}

//权限查询
function GetAuthority() {
    var url = '/Base/Authority/GetAuthorityByUserID?rdo=' + Math.random();
    $.ajax({
        type: "post",
        url: url,
        contentType: "application/json;charset=utf-8",
        async: false,
        success: function (data) {
            var authorityCode = "<input type='hidden' id='AuthorityCodes' name='AuthorityCodes' value='" + data + "' />";
            $("body").append(authorityCode);
        },
        error: function (msg) {
            return;
        }
    });
}

/*
附件查看使用
*/
//检查文件格式[附件信息]
function GetFileSuffix(fileName) {
    //分割上传文件字符串  userfile的value为上传文件的名称 类型为字符串。
    var fileNameArr = fileName.split('.');
    //文件名后缀
    var suffix = fileNameArr[fileNameArr.length - 1];
    var PDF = ".pdf";
    if (PDF.indexOf(suffix.toLowerCase()) >= 0) {
        return true;
    }
    else {
        return false;
    }
}

//遮罩层
function LoadingModelPage(bFlg, appendDiv) {
    if (appendDiv == undefined) appendDiv = "body";

    if (bFlg == false) {
        $("#loadingModelPage").remove();
        return;
    }
    var is = $("#loadingModelPage").length > 0;
    if (is == false) {
        var load = '<div id="loadingModelPage" style="position: absolute; left: 0px; top: 0px; width: 100%; height: 100%; background: rgba(0,0,0,0.3); z-index: 9999; display: block;"><div style="position: relative; left: 0px; top: 0px; width: 100%; height: 100%; display: flex; justify-content: center; align-items: Center;"><i class ="fa-li fa fa-spinner fa-spin" style="font-size: 45px; position: absolute; left: 50%; top: 50%; width: 50px; height: 50px; color: #fff; margin-left: -25px; margin-top: -25px;"></i><p style="color: #fff; margin-top: 70px;">数据正在处理中，请稍等。</p></div></div>';
        $(appendDiv).append(load);
    } else {
        $("#loadingModelPage").show();
    }
}

//生成主键
var Guid = {
    NewGuid: function () {
        var guid = (this._G() + this._G() + "-" + this._G() + "-" + this._G() + "-" + this._G() + "-" + this._G() + this._G() + this._G()).toLowerCase();
        return guid;
    },
    _G: function () {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }
};

//数字类型的值添加千位分隔符保留2位小数位
//value 值
//isToFixed 是否需要格式化小数位
//decimalNumber 需要保留的小数位数
//isSplitChar 是否需要千分位分割符
function milliFormat(value, isToFixed, decimalNumber, isSplitChar) {
    if (value == "" || value == undefined || !value) {
        return value;
    } else {
        if (/[^0-9\.]/.test(value)) return "invalid value";
        if (isToFixed) {//需要保留2位小数
            value = value.toFixed(decimalNumber).toString();
        } else {
            value = value.toString();
        }
        if (isSplitChar) {
            //正则表达式实现千分位分隔符
            var res = value.replace(/\d+/, function (n) { // 先提取整数部分
                return n.replace(/(\d)(?=(\d{3})+$)/g, function ($1) {
                    return $1 + ",";
                });
            })
            return res;
            //JS自带的函数 toLocaleString也可以实现千分位分隔符
            //value.toLocaleString();
        } else {
            return value;
        }
        
    }
}